//
//  CircleLogisticsTableViewCell.m
//  Logistics
//
//  Created by 锋 on 2018/1/18.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "CircleLogisticsTableViewCell.h"
#import "CircleContentModel.h"
#import "CircleCommentModel.h"
#import "CustomTapGestureRecognizer.h"
#import "UILabel+YBAttributeTextTapAction.h"

@implementation CircleLogisticsTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setDataArr:(NSMutableArray *)dataArr {
    _dataArr = dataArr;
    CircleContentModel *contentModel = dataArr[_indexPath.row];
//    self.commentBackgroundView.backgroundColor = UIColorHexValue(0xB4B4B4);
    NSURL *headIconUrl = [NSURL URLWithString:contentModel.userHeadImg];
    [self.headIcon sd_setImageWithURL:headIconUrl placeholderImage:nil];
    self.headIcon.userInteractionEnabled = YES;
    self.headIcon.tag = self.indexPath.row;
    UITapGestureRecognizer *iconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoOtherLogistics:)];
    [self.headIcon addGestureRecognizer:iconTap];
    self.nameLabel.text = contentModel.messageUsername;
    self.nameLabel.textColor = UIColorHexValue(0xFF576B95);
    self.commentBtn.tag = _indexPath.row;
    [self.commentBtn addTarget:self action:@selector(onClickCommentBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.cellContentLabel.text = contentModel.content;
    // 计算firstCommentLabel文本高度
    CGRect textViewHeight = [Utilities calculateWidthAndHeightWithWidth:self.cellContentLabel.frame.size.width height:1000 text:self.cellContentLabel.text font:[UIFont systemFontOfSize:15]];
    CGFloat firstaHeight = textViewHeight.size.height - 21 > 0 ? textViewHeight.size.height - 21 : 0;
    CGFloat maxHeight = self.cellContentLabel.frame.size.height + firstaHeight;
//    if (maxHeight > 31.03) {
//        maxHeight = 31.03;
//    }
    [self.cellContentLabel setFrame:CGRectMake(self.cellContentLabel.frame.origin.x, self.cellContentLabel.frame.origin.y, self.cellContentLabel.frame.size.width, maxHeight)];
    
    self.addressLabel.text = contentModel.userAddress;
    NSString *str = [self timeIntervalFromLastTime:contentModel.createDtm lastTimeFormat:@"yyyy-MM-dd HH:mm:ss"];
    self.timeLabel.text = str;
    self.messageTypeButton.layer.borderWidth = 1;
    self.messageTypeButton.layer.borderColor = UIColorHexValue(0xFF576B95).CGColor;
    [self.messageTypeButton setTitle:contentModel.tag forState:UIControlStateNormal];
    self.messageTypeButton.titleLabel.textColor = UIColorHexValue(0xFF576B95);
    self.addressLabel.textColor = UIColorHexValue(0xFF576B95);
    NSString *str1=contentModel.imgs;
    NSArray *temp;
    if (str1 && ![str1 isEqual:@""]) {
        if ([str1 containsString:@","]) {
            temp=[str1 componentsSeparatedByString:@","];
        } else {
            temp=@[str1];
        }
    }
    CGFloat y = 0;
    if (temp.count>0) {
        CGFloat width = (self.pictureBackgroundView.frame.size.width-2*5)/3;
        for (int i = 0; i<temp.count; i++) {
            if (i > 2) {
                NSInteger line = i / 3;
                y = line * 5 + line * width;
            }
            NSInteger row = i % 3;
            UIImageView *imageView = [ZCControl createImageViewWithFrame:CGRectMake(5*row+row*width, y, width, width) ImageName:nil];
            NSURL *pictureUrl = [NSURL URLWithString:temp[i]];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            [imageView sd_setImageWithURL:pictureUrl placeholderImage:nil];
            imageView.tag = i+100;
            imageView.userInteractionEnabled = YES;
            CustomTapGestureRecognizer *showImageTap = [[CustomTapGestureRecognizer alloc] initWithTarget:self action:@selector(showImageAction:)];
            showImageTap.delegate = self;
            showImageTap.indexNum = self.indexPath.row;
            showImageTap.pictureIndexNum = i;
            [imageView addGestureRecognizer:showImageTap];
//            self.pictureBackgroundView.userInteractionEnabled = YES;
            [self.pictureBackgroundView addSubview:imageView];
        }
        self.pictureBackgroundView.frame = CGRectMake(self.pictureBackgroundView.frame.origin.x, CGRectGetMaxY(self.cellContentLabel.frame)+10, self.pictureBackgroundView.frame.size.width, y+width);
//        NSString *addressStr = [LTools cacheForKey:SERVER_Address];
        if (!contentModel.location || [contentModel.location isKindOfClass:[NSNull class]]) {
            self.addressLabel.hidden = YES;
            self.timeLabel.frame = CGRectMake(self.timeLabel.frame.origin.x, CGRectGetMaxY(self.pictureBackgroundView.frame)+5, self.timeLabel.frame.size.width, self.timeLabel.frame.size.height);
            self.commentBtn.frame = CGRectMake(self.commentBtn.frame.origin.x, CGRectGetMaxY(self.pictureBackgroundView.frame)+7, self.commentBtn.frame.size.width, self.commentBtn.frame.size.height);
        } else {
            self.addressLabel.text = contentModel.location;
            self.addressLabel.frame = CGRectMake(self.addressLabel.frame.origin.x, CGRectGetMaxY(self.pictureBackgroundView.frame)+5, self.addressLabel.frame.size.width, self.addressLabel.frame.size.height);
            self.timeLabel.frame = CGRectMake(self.timeLabel.frame.origin.x, CGRectGetMaxY(self.addressLabel.frame)+5, self.timeLabel.frame.size.width, self.timeLabel.frame.size.height);
            self.commentBtn.frame = CGRectMake(self.commentBtn.frame.origin.x, CGRectGetMaxY(self.addressLabel.frame)+7, self.commentBtn.frame.size.width, self.commentBtn.frame.size.height);
        }
    } else {
        self.pictureBackgroundView.hidden = YES;
//        NSString *addressStr = [LTools cacheForKey:SERVER_Address];
        if (!contentModel.location || [contentModel.location isKindOfClass:[NSNull class]]) {
            self.addressLabel.hidden = YES;
            self.timeLabel.frame = CGRectMake(self.timeLabel.frame.origin.x, CGRectGetMaxY(self.cellContentLabel.frame)+5, self.timeLabel.frame.size.width, self.timeLabel.frame.size.height);
            self.commentBtn.frame = CGRectMake(self.commentBtn.frame.origin.x, CGRectGetMaxY(self.cellContentLabel.frame)+7, self.commentBtn.frame.size.width, self.commentBtn.frame.size.height);
        } else {
            self.addressLabel.text = contentModel.location;
            self.addressLabel.frame = CGRectMake(self.addressLabel.frame.origin.x, CGRectGetMaxY(self.cellContentLabel.frame)+5, self.addressLabel.frame.size.width, self.addressLabel.frame.size.height);
            self.timeLabel.frame = CGRectMake(self.timeLabel.frame.origin.x, CGRectGetMaxY(self.addressLabel.frame)+5, self.timeLabel.frame.size.width, self.timeLabel.frame.size.height);
            self.commentBtn.frame = CGRectMake(self.commentBtn.frame.origin.x, CGRectGetMaxY(self.addressLabel.frame)+7, self.commentBtn.frame.size.width, self.commentBtn.frame.size.height);
        }
    }
    if (contentModel.comments.count>0) {
        CGFloat maxComment = 0;
        CGFloat commentLabelH = 0;
        for (int i=0; i<contentModel.comments.count; i++) {
            CircleCommentModel *model = contentModel.comments[i];
            NSString *contentStr = [NSString stringWithFormat:@"%@：%@", model.commentUserName, model.content];
            NSString *tapStr = [NSString stringWithFormat:@"%@：", model.commentUserName];
            UILabel *commentLabel = [ZCControl createLabelWithFrame:CGRectMake(10, i*21+10, self.commentBackgroundView.frame.size.width-20, 21) Font:14 Text:contentStr Color:nil];
            
            // 计算firstCommentLabel文本高度
            CGRect textViewHeight = [Utilities calculateWidthAndHeightWithWidth:self.commentBackgroundView.frame.size.width-20 height:1000 text:contentStr font:[UIFont systemFontOfSize:14]];
            CGFloat firstaHeight = textViewHeight.size.height - 21 > 0 ? textViewHeight.size.height - 21 : 0;
            CGFloat maxHeight = 21 + firstaHeight;
            //    if (maxHeight > 31.03) {
            //        maxHeight = 31.03;
            //    }
            [commentLabel setFrame:CGRectMake(10, commentLabelH+10, self.commentBackgroundView.frame.size.width-20, maxHeight)];
            commentLabelH += maxHeight;
            
            NSMutableAttributedString *nicknameStr = [[NSMutableAttributedString alloc] initWithString:contentStr];
            [commentLabel yb_addAttributeTapActionWithStrings:@[tapStr] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
                [self gotoMineVC:i andCellIndex:_indexPath.row];
            }];
            [nicknameStr addAttribute:NSForegroundColorAttributeName value:UIColorHexValue(0xFF576B95) range:NSMakeRange(0, tapStr.length)];
            [nicknameStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, nicknameStr.length)];
            commentLabel.attributedText = nicknameStr;
            //设置是否有点击效果，默认是YES
            commentLabel.enabledTapEffect = NO;
            if (i==contentModel.comments.count-1) {
                maxComment = CGRectGetMaxY(commentLabel.frame);
            }
            [self.commentBackgroundView addSubview:commentLabel];
        }
        self.triangleImageView.frame = CGRectMake(self.triangleImageView.frame.origin.x, CGRectGetMaxY(self.timeLabel.frame)+12-self.triangleImageView.frame.size.height, self.triangleImageView.frame.size.width, self.triangleImageView.frame.size.height);
        self.commentBackgroundView.frame = CGRectMake(self.commentBackgroundView.frame.origin.x, CGRectGetMaxY(self.timeLabel.frame)+5, self.commentBackgroundView.frame.size.width, maxComment+10);
        self.cellHeight = CGRectGetMaxY(self.commentBackgroundView.frame)+15;
    } else {
        self.commentBackgroundView.hidden = YES;
        self.cellHeight = CGRectGetMaxY(self.timeLabel.frame)+15;
    }
}

- (NSString *)timeIntervalFromLastTime:(NSString *)lastTime lastTimeFormat:(NSString *)format1
{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //当前时间
    //    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    //    dateFormatter2.dateFormat = @"yyyy/MM/dd HH:mm:ss";
    //    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
    return [self timeIntervalFromLastTime:lastDate ToCurrentTime:[NSDate date]];
    
}
- (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime
{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    //秒、分、小时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;
    
    if (minutes <= 10)
    {
        return  @"刚刚";
    }
    else if (minutes < 60)
    {
        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }
    else if (hours < 24)
    {
        return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30)
    {
        return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12)
    {
        return [NSString stringWithFormat: @"%ld月前",(long)month];
    }
    else if (yers >= 1){
        return [NSString stringWithFormat: @"%ld月前",(long)yers];
    }
    return @"";
}

- (void)showImageAction:(CustomTapGestureRecognizer *)showTap
{
    if ([self.delegate respondsToSelector:@selector(showImageWithIndexPath:imageIndex:)]) {
        [self.delegate showImageWithIndexPath:showTap.indexNum imageIndex:showTap.pictureIndexNum];
    }
}

- (void)gotoOtherLogistics:(UITapGestureRecognizer *)tap {
    if ([self.delegate respondsToSelector:@selector(gotoCircleLogistics:)]) {
        CircleContentModel *model = self.dataArr[tap.view.tag];
        [self.delegate gotoCircleLogistics:model.userId];
    }
}

- (void)gotoMineVC:(NSInteger)num andCellIndex:(NSInteger)index {
    if ([self.delegate respondsToSelector:@selector(gotoMineVC:andCellIndex:)]) {
        [self.delegate gotoMineVC:num andCellIndex:index];
    }
}

- (void)onClickCommentBtn:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(onClickCommentBtn:)]) {
        [self.delegate onClickCommentBtn:sender];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isEqual:[UITableViewCell class]]) {
        return NO;
    }
    return YES;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
